package com.wms.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wms.dto.StoragePageQueryDTO;
import com.wms.entity.WmsGoods;
import com.wms.entity.WmsStorage;
import com.wms.exception.StorageDeleteException;
import com.wms.mapper.GoodsMapper;
import com.wms.mapper.StorageMapper;
import com.wms.result.PageResult;
import com.wms.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class StorageServiceImpl implements StorageService {
    @Autowired
    private StorageMapper storageMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 分页查询
     * @param storagePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(StoragePageQueryDTO storagePageQueryDTO) {
        log.info("分页查询仓库信息:{}", storagePageQueryDTO);
        PageHelper.startPage(storagePageQueryDTO.getPage(), storagePageQueryDTO.getPageSize());
        Page<WmsStorage> page = storageMapper.pageQuery(storagePageQueryDTO);
        long total = page.getTotal();
        List<WmsStorage> result = page.getResult();
        return new PageResult(total, result);
    }

    /**
     * 新增仓库
     * @param storage
     */
    @Override
    public void save(WmsStorage storage) {
        log.info("新增仓库:{}", storage);
        storageMapper.save(storage);
    }

    /**
     * 修改仓库
     * @param storage
     */
    @Override
    public void update(WmsStorage storage) {
        log.info("修改仓库:{}", storage);
        storageMapper.update(storage);
    }

    /**
     * 删除仓库
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        log.info("删除仓库:{}", ids);
        // 判断仓库中是否存在物品
        for (Long id : ids) {
            List<WmsGoods> wmsGoods = goodsMapper.getByStorageId(id);
            // 若是存在物品则无法删除
            if (wmsGoods.size() > 0) {
                throw new StorageDeleteException("该仓库中存在物品，无法删除");
            }
        }
        storageMapper.delete(ids);
    }

    /**
     * 根据id查询仓库
     * @param id
     * @return
     */
    @Override
    public WmsStorage getById(Long id) {
        WmsStorage storage = storageMapper.getById(id);
        return storage;
    }

    /**
     * 查询所有仓库
     * @return
     */
    public List<WmsStorage> getAll(){
        return storageMapper.getAll();
    }
}
